package com.csc.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.csc.constants.Constants;
import com.csc.domain.Account;
import com.csc.domain.Transaction;
import com.csc.domain.User;
import com.csc.service.AccountService;
import com.csc.service.CustomerService;
import com.csc.service.TransactionService;

@Controller
public class SupportController {

	@Autowired
	private CustomerService customerService;

	@Autowired
	private AccountService accountService;

	@Autowired
	private TransactionService transactionService;

	static final Logger logger = Logger.getLogger(SupportController.class);

	/**
	 *  ADD FUNDS
	 */
	
	// TUAN
	@RequestMapping(value="/sendAddRequest", method = RequestMethod.GET)
	public String doAddFund(Model model, @RequestParam("accNumber") String accNumber, HttpServletRequest request){
		HttpSession session = request.getSession();
		logger.info("=====" + accNumber + "Add Funds is calling........ !!!");
		Account examAccount = accountService.findAccountInfoByAccountInfoNumber(accNumber);
		session.setAttribute("addAccount", examAccount);
		if(examAccount == null){
			return "searchAccount";
		}
		model.addAttribute("examAccount", examAccount);
		return "addFunds";
	}
	
	@RequestMapping(value = "/addConfirm", method = RequestMethod.POST)
	public String doAddConfirm(Model model, HttpServletRequest request) {
		logger.info("Add Confirm");

		HttpSession session = request.getSession();

		String amounttxt = request.getParameter("moneyAdd");

		Account examAccount = (Account) session.getAttribute("addAccount");

		if (amounttxt.equals("")) {
			String error = "Add Amount cannot be empty";
			model.addAttribute("error", error);

			model.addAttribute("examAccount", examAccount);
			return "addFunds";
		}
		logger.info("add Confirm" + amounttxt);

		session.setAttribute("doubleAmount", amounttxt);
		model.addAttribute("examAccount", examAccount);
		return "addConfirm";
	}

	@RequestMapping(value = "/addComplete", method = RequestMethod.POST)
	public String doAddComplete(Model model, HttpServletRequest request) {
		logger.info("========   Add Complete is calling...... !!!!!!!");
		HttpSession session = request.getSession();
		Account examAccount = (Account) session.getAttribute("addAccount");

		logger.info("=============================Exam Account of CompleteAdd"
				+ examAccount);
		Double doubleAmount = Double.parseDouble((String) session
				.getAttribute("doubleAmount"));
		logger.info("=============================Amount of CompleteAdd"
				+ doubleAmount);
		Double remainMoney = examAccount.getBalance() + doubleAmount;
		logger.info("Remain Money ========== " + remainMoney);
		DateFormat dateFormat = new SimpleDateFormat(
				Constants.SIMPLE_FORMAT_DATE);
		Date date = new Date();
		String currentDate = dateFormat.format(date);
		logger.info("Get Current Date: ============  " + currentDate);
		if (remainMoney < 0) {
			String error = "Add amount is greater than your current balance !";
			model.addAttribute("error", error);
			model.addAttribute("examAccount", examAccount);
			return "addFunds";
		}
		// int customerId = examAccount.getIdCustomer();
		// Customer examCustomer = accountService.getCustomerById(customerId);
		model.addAttribute("examAccount", examAccount);
		model.addAttribute("doubleAmount", doubleAmount);
		model.addAttribute("remainMoney", remainMoney);
		model.addAttribute("currentDate", currentDate);

		return "addComplete";
	}

	@RequestMapping(value = "/addSuccessfulComplete", method = RequestMethod.POST)
	public String doAddCompleteSuccess(Model model,
			@RequestParam("accountId") String accId,
			@RequestParam("addAmount") double doubleAmount,
			@RequestParam("beginTime") String date, HttpServletRequest request)
			throws ParseException {
		logger.info("go to Add Transaction ....... ");

		Account tempAccount = accountService.findAccountInfoById(Integer
				.parseInt(accId));
		
		HttpSession session = request.getSession();
		User userSupport = (User) session.getAttribute("user");
		
		// create add funds transaction in database
		
		boolean check = transactionService.createAddFundsTransaction(doubleAmount, tempAccount, userSupport);
		
		if (check == false) {
			String error = "Add Transaction is Failed ";
			model.addAttribute("error", error);
			return "addComplete";
		}
		logger.info("Add Complete Test tempAccount: =========" + tempAccount);
		return "searchAccount";
	}

	/**
	 *  WITHDRAWS
	 */

	@RequestMapping(value = "/sendWithdrawRequest", method = RequestMethod.GET)
	public String doWithdrawFund(Model model,
			@RequestParam("accNumber") String accNumber,
			HttpServletRequest request) {
		HttpSession session = request.getSession();
		logger.info("=====" + accNumber
				+ "withdraw Funds is calling........ !!!");
		Account examAccount = accountService
				.findAccountInfoByAccountInfoNumber(accNumber);
		session.setAttribute("withdrawAccount", examAccount);
		if (examAccount == null) {
			return "redirect:/";
		}
		model.addAttribute("examAccount", examAccount);
		return "withdrawFunds";
	}

	@RequestMapping(value = "/withdrawConfirm", method = RequestMethod.POST)
	public String doWithdrawConfirm(Model model, HttpServletRequest request) {
		logger.info("withdraw Confirm");

		HttpSession session = request.getSession();

		String amounttxt = request.getParameter("moneyWithdraw");

		Account examAccount = (Account) session.getAttribute("withdrawAccount");

		if (amounttxt.equals("")) {
			String error = "Withdraw Amount cannot be empty";
			model.addAttribute("error", error);

			model.addAttribute("examAccount", examAccount);
			return "withdrawFunds";
		}
		logger.info("withdraw Confirm" + amounttxt);

		session.setAttribute("doubleAmount", amounttxt);
		model.addAttribute("examAccount", examAccount);
		return "withdrawConfirm";
	}

	@RequestMapping(value = "/withdrawComplete", method = RequestMethod.POST)
	public String doWithdrawComplete(Model model, HttpServletRequest request) {
		logger.info("========   Withdraw Complete is calling...... !!!!!!!");
		HttpSession session = request.getSession();
		Account examAccount = (Account) session.getAttribute("withdrawAccount");

		logger.info("=============================Exam Account of CompleteWithdraw"
				+ examAccount);
		Double doubleAmount = Double.parseDouble((String) session
				.getAttribute("doubleAmount"));
		logger.info("=============================Amount of CompleteWithdraw"
				+ doubleAmount);
		Double remainMoney = examAccount.getBalance() - doubleAmount;
		logger.info("Remain Money ========== " + remainMoney);
		DateFormat dateFormat = new SimpleDateFormat(
				Constants.SIMPLE_FORMAT_DATE);
		Date date = new Date();
		String currentDate = dateFormat.format(date);
		logger.info("Get Current Date: ============  " + currentDate);
		if (remainMoney < 0) {
			String error = "Withdraw amount is greater than your current balance !";
			model.addAttribute("error", error);
			model.addAttribute("examAccount", examAccount);
			return "withdrawFunds";
		}
		// int customerId = examAccount.getIdCustomer();
		// Customer examCustomer = accountService.getCustomerById(customerId);
		model.addAttribute("examAccount", examAccount);
		model.addAttribute("doubleAmount", doubleAmount);
		model.addAttribute("remainMoney", remainMoney);
		model.addAttribute("currentDate", currentDate);

		return "withdrawComplete";
	}

	@RequestMapping(value = "/withdrawCompleteSuccess", method = RequestMethod.POST)
	public String doWithdrawCompleteSuccess(Model model,
			@RequestParam("accountId") String accId,
			@RequestParam("withdrawAmount") double doubleAmount,
			@RequestParam("beginTime") String date, HttpServletRequest request)
			throws ParseException {
		logger.info("go to Success Withdraw Transaction ....... ");

		logger.info("=================== Test Withdraw" + accId + " " + date
				+ " " + doubleAmount);
		Account tempAccount = accountService.findAccountInfoById(Integer
				.parseInt(accId));
		logger.info("Withdraw Complete Test tempAccount: ========="
				+ tempAccount);
		HttpSession session = request.getSession();

		User userSupport = (User) session.getAttribute("user");


		// create withdraw transaction in database
		boolean check = transactionService.createWithdrawTransaction(doubleAmount, tempAccount, userSupport);

		if (check == false) {
			String error = "Withdraw Transaction is Failed ";
			model.addAttribute("error", error);
			return "withdrawComplete";
		}
		logger.info("Withdraw Complete Test userSupport: ========="
				+ userSupport);

		return "searchAccount";
	}
	
	/**
	 *  TRANSFER
	 */

	// TrangNguyen - page add information for transfer transaction
	@RequestMapping(value = "/transferTransAdd", method = RequestMethod.GET)
	public String doTransferTransAdd(HttpServletRequest request, Model model) {
		String senderAccountNumber = request
				.getParameter("senderAccountNumber");
		logger.info("Sender Account Number = " + senderAccountNumber);
		Account account = accountService
				.findAccountInfoByAccountInfoNumber(senderAccountNumber);
		if (account == null) {
			model.addAttribute("error", "Sender Account Number = "
					+ senderAccountNumber + " not exist");
			return "transferTransAdd";
		}

		// Validation from transferTransConfirm
		model.addAttribute("validSendAmount",
				request.getParameter("validSendAmount"));
		model.addAttribute("validReceiveAccount",
				request.getParameter("validReceiveAccount"));
		model.addAttribute("senderAccountInfo", account);

		return "transferTransAdd";
	}

	// TrangNguyen - verify information valid
	@RequestMapping(value = "/transferTransConfirm", method = RequestMethod.POST)
	public String doTransferTransConfirm(HttpServletRequest request, Model model) {
		String senderAccountNumber = request
				.getParameter("senderAccountNumber");
		String receiverAccountNumber = request
				.getParameter("receiverAccountNumber");
		String amountTransfer = request.getParameter("amountMoneyTransfer");
		boolean check = true;
		Account senderAccount = accountService
				.findAccountInfoByAccountInfoNumber(senderAccountNumber);
		if (senderAccount == null) {
			model.addAttribute("error", "Sender Account Number = "
					+ senderAccountNumber + "not exist");
			return "transferTransConfirm";
		} else {
			if (Integer.parseInt(amountTransfer) > senderAccount.getBalance()) {
				model.addAttribute("validSendAmount",
						"Money not enough to send");
				check = false;
			}
		}

		Account receiverAccount = accountService
				.findAccountInfoByAccountInfoNumber(receiverAccountNumber);
		if (receiverAccount == null) {
			model.addAttribute("validReceiveAccount",
					"Account number not exist");
			check = false;
		} else {
			if (senderAccountNumber.equals(receiverAccountNumber)) {
				model.addAttribute("validReceiveAccount",
						"Can't transfer same account");
				check = false;
			}
		}

		if (check == false) {
			model.addAttribute("senderAccountNumber", senderAccountNumber);
			return "redirect:/transferTransAdd.html";
		}
		model.addAttribute("senderAccount", senderAccount);
		model.addAttribute("receiverAccount", receiverAccount);
		model.addAttribute("amountTransfer", amountTransfer);
		return "transferTransConfirm";
	}

	// TrangNguyen -
	@RequestMapping(value = "/transferTransComplete", method = RequestMethod.GET)
	public String doTransferTransComplete(HttpServletRequest request,
			Model model) {
		HttpSession session = request.getSession();
		String senderAccountNumber = request
				.getParameter("senderAccountNumber");
		String receiverAccountNumber = request
				.getParameter("receiverAccountNumber");
		String amountTransfer = request.getParameter("amountMoneyTransfer");
		Account senderAccount = accountService
				.findAccountInfoByAccountInfoNumber(senderAccountNumber);
		Account receiverAccount = accountService
				.findAccountInfoByAccountInfoNumber(receiverAccountNumber);
		User userSupport = (User) session.getAttribute("user");
		// create transfer transaction in database
		boolean check = transactionService.createTransferTransaction(amountTransfer,senderAccountNumber,receiverAccountNumber, userSupport );
		
		if (check == false) {
			model.addAttribute("error", "Insert new transfer transction fail");
			return "transferTransComplete";
		}
		
		model.addAttribute("senderAccount", senderAccount);
		model.addAttribute("receiverAccount", receiverAccount);
		model.addAttribute("amountTransfer", amountTransfer);
		model.addAttribute("success", "Create transfer transaction success");
		return "transferTransComplete";
	}

}
